//
//  DBHelper+Merge_MineAndFavor.m
//  KidReading
//
//  Created by YangShuai on 17/2/20.
//  Copyright © 2017年 刘赞黄Telen. All rights reserved.
//

#import "DBHelper+Merge_MineAndFavor.h"
#import "ConstDefine.h"

@implementation TABLE_BOOKS_MergeMineANDFavor
+ (NSString*)tableName{return @"MyBooksAndFavor";}
+ (NSString *)primaryKey{return @"primary key(userId,bookId,mergeType)";}
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" userId='%@' and bookId = '%@' and mergeType = '%@'",@(_userId),@(_bookId),@(_mergeType)];}
@end

@implementation TABLE_BOOKS_MergeMineANDFavor_TEMP
+ (NSString*)tableName{return @"MyBooksAndFavor_Temp";}
+ (NSString *)primaryKey{return @"primary key(userId,bookId,mergeType)";}
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" userId='%@' and bookId = '%@' and mergeType = '%@'",@(_userId),@(_bookId),@(_mergeType)];}
@end

@implementation TABLE_BOOKS_MergeTimestamp
+ (NSString*)tableName{return @"MergeTimestamp";}
+ (NSString *)primaryKey{return @"primary key(userId,mergeType)";}
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" userId='%@' and mergeType = '%@'",@(_userId),@(_mergeType)];}
@end

@implementation TABLE_BOOKS_AudioSort
+ (NSString*)tableName{return @"AudioPlaySort";}
+ (NSString *)primaryKey{return @"primary key(userId)";}
- (NSString *)byPrimaryKey{return [NSString stringWithFormat:@" userId='%@'",@(_userId)];}
@end


@implementation DBHelper (Merge_MineAndFavor)
ASSOCIATED(mergeMineAndFavor_dbQue, setMergeMineAndFavor_dbQue, JRFMDatabaseQueue*, OBJC_ASSOCIATION_RETAIN_NONATOMIC)

+ (void)load{
    [self swizzleSelector:@selector(init) withSelector:@selector(init_MergeMineAndFavor)];
}

- (void)update_VersionForMergeDB:(JRFMDatabase*)db
{
    long ver = [JRFMDatabase JRFMDB_getVersionFromDB:db];
    if (ver <= 0) {
        [JRFMDatabase JRFMDB_setDB:db version:2];//Version 3.0.0开发使用 //1->2.0.1
    }
}

- (instancetype)init_MergeMineAndFavor
{
    self = [self init_MergeMineAndFavor];
    if (self) {
        BOOL debugDB = YES;
#if __KeyForDB_ON_
        debugDB = NO;
#endif
        NSString* path = [self getDBPath:__DBFileName_MergeMineAndFavor debugPath:__DBFileName_MergeMineAndFavor_debug dbKey:__KeyForDB_ dbebug:debugDB];
        [self dbFile_initForDBPath:path];
        self.mergeMineAndFavor_dbQue = [JRFMDatabaseQueue databaseQueueWithPath:path];
        [self.mergeMineAndFavor_dbQue inDatabase:^(JRFMDatabase *db) {
#if __KeyForDB_ON_
            if (![db setKey:__KeyForDB_]) {
                NSLog(@"setkey failed");
            };
#endif
            //
            [db executeUpdate:[TABLE_BOOKS_MergeMineANDFavor createTable]];
            [db executeUpdate:[TABLE_BOOKS_MergeMineANDFavor_TEMP createTable]];
            [db executeUpdate:[TABLE_BOOKS_MergeTimestamp createTable]];
            [db executeUpdate:[TABLE_BOOKS_AudioSort createTable]];
            //
            [self update_VersionForMergeDB:db];
        }];
        //
    }
    return self;
}

//添加我的图书或者我的收藏数据
- (void)Merge_MineAndFavor_updateListWithIsTempTable:(BOOL)isTampTable dictArr:(NSArray*)dictList complete:(void (^)(void))comp{
    NSString* tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor class]);
    if (isTampTable) {
        tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor_TEMP class]);
    }
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self updateListToTableClass:tableClassName dictArr:dictList db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
- (void)Merge_MineAndFavor_updateListWithIsTempTable:(BOOL)isTampTable tbArr:(NSArray*)tbList complete:(void (^)(void))comp{
    NSMutableArray* dictList = [NSMutableArray new];
    for (TABLE_BOOKS* bookModel in tbList) {
        NSDictionary* bookDict = [bookModel JRMJ_keyValues];
        [dictList addObject:bookDict];
    }
    [self Merge_MineAndFavor_updateListWithIsTempTable:isTampTable dictArr:dictList complete:comp];
}

//删除的图书或者我的收藏数据
- (void)Merge_MineAndFavor_deletListWithIsTempTable:(BOOL)isTampTable dictArr:(NSArray*)dictList complete:(void (^)(void))comp{
    NSString* tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor class]);
    if (isTampTable) {
        tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor_TEMP class]);
    }
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self deletListToTableClass:tableClassName dictArr:dictList db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
- (void)Merge_MineAndFavor_deletListWithIsTempTable:(BOOL)isTampTable tbArr:(NSArray*)tbList complete:(void (^)(void))comp{
    NSString* tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor class]);
    if (isTampTable) {
        tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor_TEMP class]);
    }
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self deletListToTableClass:tableClassName tbArr:tbList db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
//查询的图书或者我的收藏数据
- (void)Merge_MineAndFavor_getDictList:(void(^)(NSArray* list))retlist WithIsTempTable:(BOOL)isTampTable where:(NSString*)wheresql{
    NSString* tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor class]);
    if (isTampTable) {
        tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor_TEMP class]);
    }
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            NSArray * arr = [self getDictList_fromTableClass:tableClassName where:wheresql db:db];
            [DataProcess do_Main_quick:^{
                retlist(arr);
            }];
        }];
    }];
}
- (void)Merge_MineAndFavor_getList:(void(^)(NSArray* list))retlist WithIsTempTable:(BOOL)isTampTable where:(NSString*)wheresql{
    NSString* tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor class]);
    if (isTampTable) {
        tableClassName = NSStringFromClass([TABLE_BOOKS_MergeMineANDFavor_TEMP class]);
    }
    [self Merge_MineAndFavor_getDictList:^(NSArray *list) {
        [DataProcess do_Async_quick:^{
            NSMutableArray* marr = [NSMutableArray new];
            [list enumerateObjectsUsingBlock:^(NSDictionary*  _Nonnull dict, NSUInteger idx, BOOL * _Nonnull stop) {
                id obj = [NSClassFromString(tableClassName) JRMJ_objectWithKeyValues:dict];
                if ([obj isKindOfClass:[TABLE_base class]]) {
                    NSDictionary* replaceKeys = [[obj class] replacedKeyFromPropertyName];
                    for (NSString* key in replaceKeys) {
                        id value = dict[key];
                        if (value && [obj hasProperty:key]) {
                            [obj setValue:value forKey:key];
                        }
                    }
                }
                if (obj) {
                    [marr addObject:obj];
                }
            }];
            [DataProcess do_Main_quick:^{
                retlist(marr);
            }];
        }];
    } WithIsTempTable:isTampTable where:wheresql];
}

#pragma mark - 对于时间戳的操作
//对于时间戳的操作
- (void)Merge_MineAndFavor_updateMergeTimestampWithNewTimestamp:(long long)newTimestamp MergeType:(MergeType)mergeType completed:(void (^)(void))comp{
    [DataProcess do_Async_quick:^{
        UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        NSDictionary* dict = @{@"userId":@(uinfo.uid),@"mergeType":@(mergeType),@"server_timestamp":@(newTimestamp)};
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self updateListToTableClass:NSStringFromClass([TABLE_BOOKS_MergeTimestamp class]) dictArr:@[dict] db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
- (void)Merge_MineAndFavor_deleteUserMergeTimestampWithMergeType:(MergeType)mergeType Completed:(void (^)(void))comp{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSDictionary* dict = @{@"userId":@(uinfo.uid),@"mergeType":@(mergeType)};
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self deletListToTableClass:NSStringFromClass([TABLE_BOOKS_MergeTimestamp class]) dictArr:@[dict] db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
- (void)Merge_MineAndFavor_getUserMergeTimestampWithMergeType:(MergeType)mergeType Completed:(void(^)(long long timestamp))comp{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            NSArray * arr = [self getDictList_fromTableClass:NSStringFromClass([TABLE_BOOKS_MergeTimestamp class]) where:[NSString stringWithFormat:@"where userId = '%@' and mergeType = '%@'",@(uinfo.uid),@(mergeType)] db:db];
            NSDictionary* dict = [arr firstObject];
            [DataProcess do_Main_quick:^{
                comp([dict[@"server_timestamp"] longLongValue]);
            }];
        }];
    }];
}

#pragma mark - audioSortStr
- (void)Merge_MineAndFavor_updateAudioSortWithSortStr:(NSString*)sortStr completed:(void (^)(void))comp{
    [DataProcess do_Async_quick:^{
        UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
        NSDictionary* dict = @{@"userId":@(uinfo.uid),@"listSortString":sortStr};
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self updateListToTableClass:NSStringFromClass([TABLE_BOOKS_AudioSort class]) dictArr:@[dict] db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
- (void)Merge_MineAndFavor_deleteAudioSortWithSortStr:(NSString*)sortStr Completed:(void (^)(void))comp{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    NSDictionary* dict = @{@"userId":@(uinfo.uid)};
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            [self deletListToTableClass:NSStringFromClass([TABLE_BOOKS_AudioSort class]) dictArr:@[dict] db:db];
            if (comp) {
                [DataProcess do_Main_quick:^{
                    comp();
                }];
            }
        }];
    }];
}
- (void)Merge_MineAndFavor_getAudioSortCompleted:(void(^)(NSString* sortStr))comp{
    UserInfo* uinfo = [CacheData shareSingle].getUserLoginInfo;
    [DataProcess do_Async_quick:^{
        [self.mergeMineAndFavor_dbQue inTransaction:^(JRFMDatabase *db, BOOL *rollback) {
            NSArray * arr = [self getDictList_fromTableClass:NSStringFromClass([TABLE_BOOKS_AudioSort class]) where:[NSString stringWithFormat:@"where userId = '%@'",@(uinfo.uid)] db:db];
            NSDictionary* dict = [arr firstObject];
            [DataProcess do_Main_quick:^{
                comp(dict[@"listSortString"]);
            }];
        }];
    }];
}


@end
